package cn.xy.base.server.configure;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.xy.base.server.config.AppConfig;
import cn.xy.base.server.consts.AuthConsts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * swagger基本配置<br>
 *
 *  @author xy
 */
@Slf4j
@Configuration
@EnableSwagger2WebMvc
@Profile(value = {"dev", "stage", "test"})
public class SwaggerConfiguration {

    @Resource
    private AppConfig appConfig;

    /**
     * @return Docket
     */
    @Bean
    public Docket sysAdmApiDocket() {
        return newGroupDocket("系统基础管理端接口", "cn.xy.base.server.controller.admapi", AuthConsts.ADMIN_AUTHORIZATION_HEADER);
    }


    /**
     * @return Docket
     */
    @Bean
    public Docket admApiDocket() {
        return newGroupDocket("管理端接口", "com.rustic.server.controller.admapi", AuthConsts.ADMIN_AUTHORIZATION_HEADER);
    }

    /**
     * @return Docket
     */
    @Bean
    public Docket apiDocket() {
        return newGroupDocket("前端接口", "com.rustic.server.controller.api", AuthConsts.FRONT_AUTHORIZATION_HEADER);
    }

    /**
     * Swagger2创建该Api的基本信息
     *
     * @return ApiInfo
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("系统API接口RESTful APIs")
                .description("spring Boot 中构建RESTful API")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }

    /**
     * 创建一个分组文档
     *
     * @param groupName 分组名称
     * @param packages  包
     * @param tokenName token名称
     * @return Docket
     */
    private Docket newGroupDocket(String groupName, String packages, String tokenName) {
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        if (CharSequenceUtil.isNotBlank(appConfig.getSwaggerHost())) {
            docket = docket.host(appConfig.getSwaggerHost());
        }
        if (CharSequenceUtil.isNotBlank(appConfig.getSwaggerPathMapping())) {
            docket = docket.pathMapping(appConfig.getSwaggerPathMapping());
        }
        //header或参数,可添加多个
        ParameterBuilder headerParameterBuilder = new ParameterBuilder();
        headerParameterBuilder.parameterType("header")
                .name(tokenName)
                .modelRef(new ModelRef("string"))
                .required(false).build();
        return docket.groupName(groupName).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage(packages))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(CollUtil.newArrayList(headerParameterBuilder.build()));
    }

    @Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier,
                                                                         ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier,
                                                                         EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties,
                                                                         WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping =
                webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath)
                        || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes,
                corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath),
                shouldRegisterLinksMapping, null);
    }
}
